package com.wcpdoc.exam.core.dao.impl;

import com.wcpdoc.core.dao.impl.RBaseDaoImpl;
import com.wcpdoc.core.entity.PageIn;
import com.wcpdoc.core.entity.PageOut;
import com.wcpdoc.core.util.SqlUtil;
import com.wcpdoc.core.util.ValidateUtil;
import com.wcpdoc.exam.core.dao.ResourceDao;
import com.wcpdoc.exam.core.entity.Resource;
import org.springframework.stereotype.Repository;

@Repository
public class ResourceDaoImpl extends RBaseDaoImpl<Resource> implements ResourceDao {
    @Override
    public PageOut getListpage(PageIn pageIn) {

        String sql = "select \n" +
                "ID,\n" +
                "PARENT_ID ,\n" +
                "RESOURCE_NAME,\n" +
                "RESOURCE_URL,\n" +
                "RESOURCE_SIZE,\n" +
                "RESOURCE_TYPE,\n" +
                "IS_FOLDER,\n" +
                "UPDATE_TIME\n" +
                "from SYS_RESOURCE \n";
        SqlUtil sqlUtil = new SqlUtil(sql);
        sqlUtil.addWhere("STATE = 0")
                .addWhere(ValidateUtil.isValid(pageIn.get("search")), " IS_FOLDER=0 AND RESOURCE_NAME LIKE :RESOURCE_NAME", String.format("%%%s%%", pageIn.get("search")))
                .addWhere(ValidateUtil.isValid(pageIn.get("parentId",Integer.class)), "PARENT_ID = :PARENT_ID", pageIn.get("parentId",Integer.class))
        .addOrder("IS_FOLDER", SqlUtil.Order.DESC);
        return getListpage(sqlUtil, pageIn);
    }

    /**
     * 根据查询条件判断某文件夹下面是否有文件
     * @param dirName
     * @param parentId
     * @param isFolder
     * @return
     */
    @Override
    public int getCountBySelect(String dirName, Integer parentId, int isFolder) {
        String sql = "select count(1) from SYS_RESOURCE";
        SqlUtil sqlUtil = new SqlUtil(sql);
        sqlUtil.addWhere("STATE = 0")
                .addWhere("PARENT_ID = :PARENT_ID", parentId)
                .addWhere("RESOURCE_NAME = :RESOURCE_NAME", dirName)
                .addWhere("IS_FOLDER = :IS_FOLDER", isFolder);
        return getCount(sqlUtil.getSql(),parentId,dirName,isFolder);
    }


    @Override
    public int getCountByParentId(Integer parentId){
        String sql = "select count(1) from SYS_RESOURCE";
        SqlUtil sqlUtil = new SqlUtil(sql);
        sqlUtil.addWhere("STATE = 0")
                .addWhere("PARENT_ID = :PARENT_ID", parentId);
        return getCount(sqlUtil.getSql(),parentId);
    }
}
